<?php


namespace App\Services\PlatformService\Services;

use App\Enum\ZeroOneEnum;
use App\Services\BaseService;
use App\Services\PlatformService\Models\PlatformModel;

class PlatformService extends BaseService
{
    /**
     * 通过id查询用户
     * @param $id
     * @return mixed
     */
    public static function getByIdOrFail($id)
    {
        return PlatformModel::findOrFail($id);
    }

    /**
     * 根据id获取平台数据
     * @param $id
     * @return mixed
     */
    public static function getById($id)
    {
        return PlatformModel::where(['id' => $id, 'is_effect' => ZeroOneEnum::ONE])->first();
    }

    /**
     * 更新secret
     * @param $id
     * @param $secret
     * @return bool
     */
    public static function updateSecretById($id)
    {
        $model = self::getById($id);
        if (!$model) {
            return false;
        }
        $model->secret = self::randSecret();
        if ($model->save()) {
            return $model;
        }
        return false;
    }

    /**
     * 获取随机key
     * @return array
     */
    private static function randKey()
    {
        for ($i = 0; $i < 20; $i++) {
            $fun[] = rand(0, 9);
        }
        return $fun;
    }

    /**
     * 随机获取secret
     * @return string
     */
    private static function randSecret()
    {
        $letter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        for ($i = 0, $str = '', $lc = strlen($letter) - 1; $i < 32; $i++) {
            $str .= $letter[mt_rand(0, $lc)];
        }
        return $str;
    }

    /**
     * 创建平台
     * @param $data
     * @return mixed
     */
    public static function createPlatfrom($data)
    {
        $data['key'] = implode(self::randKey());
        $data['secret'] = self::randSecret();
        return PlatformModel::create($data);
    }

    public static function destroy($ids)
    {
        return PlatformModel::destroy($ids);
    }

}